const router = require('koa-router')();
const loaderData = require('../util/loaderData');
const writeData = require('../util/writeData');


let list;

// 加载列表数据
async function loaderList(){
    await loaderData('list').then(data =>{
        list = JSON.parse(data) 
    })
}

loaderList()

router.get('/', async (ctx, next) =>{
    
    let {userId} = ctx.state.token; 
    let {id} = ctx.query;
    let tags = userId ? list[userId] : [];

    if(id){
        tags = tags.filter(item =>{
            return item.id === id;
        });
    }
    
    let resData ={
        res: tags,
        msg: 'OK',
        statusCode: 200
    }
    ctx.body = resData;
    
})

router.post('/', async (ctx, next) =>{

    let reqData = ctx.request.body;
    let {userId} = ctx.state.token;
    let _list = list[userId];
    let res = {
        msg: 'OK',
        statusCode: 200,
        res: null
    }
    
    try{

        if(!reqData.id){
            let id = (_list.length + 1).toString();
            reqData.id = id;
            _list.push(reqData);
            res.res = {id};

        }else{

            for(let i=0, len=_list.length; i < len; i++){
                let item = _list[i];
                if(item.id === reqData.id){
                    _list[i] = reqData;
                    break;
                }
            }

           
        }
        
        // 写入新数据
        list[userId] = _list;
        await writeData('list.json', list);

    }catch(e){
        console.log(e)
        res = {
            msg: e,
            statusCode: 500,
            res: null
        }
    }

    ctx.body = res;
})

router.delete('/:id', async (ctx, next) =>{
    let url = ctx.path; 
    let {userId} = ctx.state.token;
    let _list = list[userId];
    let resData = {
        res: null,
        msg: 'not found tag id',
        statusCode: 400
    };

    if(url.indexOf('id') != -1){
        
        let urlArr =  url.split('=');
        let id = urlArr.pop();

        for(let i = 0, l = _list.length; i < l; i++){
            let item = _list[i];

            if(item.id === id){
                _list.splice(i, 1);
                break;
            }
        }

        list[userId] = _list;
        
        resData = {
            res: id,
            msg: 'OK',
            statusCode: 200
        }
    }

    ctx.body = resData;
    
})

module.exports = router;